#!/usr/bin/env python
# coding: utf-8

import socket
import cv2
# from matplotlib import pyplot as plt
# import matplotlib
import time
import threading
server = socket.socket()
server.bind(('0.0.0.0',8100))
print('0.0.0.0:8100')
server.listen(10)

def Server(connection,address):
    try:
        connection.settimeout(30)
        buf = connection.recv(1024)
        buf = buf.splitlines()[-1]
        cap = cv2.VideoCapture(0)
        ret,frame =cap.read()
        if(not ret or frame is None):
            cap.release()
            time.sleep(2)
            cap = cv2.VideoCapture(0)
            ret,frame =cap.read()
            if(not ret or frame is None):
                cap.release()
                time.sleep(2)
                cap = cv2.VideoCapture(0)
                ret,frame =cap.read()
                if(not ret or frame is None):
                    cap.release()
                    connection.send(b"HTTP/1.1 202 OK\r\n\r\nerrer")
                    connection.close()

        if(ret and not frame is None):
            # frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
            frame = cv2.putText(frame,buf.decode(),(10,30),cv2.FONT_HERSHEY_SIMPLEX,1.0,(50,50,50),5,cv2.LINE_AA,False)
            frame = cv2.putText(frame,buf.decode(),(10,30),cv2.FONT_HERSHEY_SIMPLEX,1.0,(255,255,255),2,cv2.LINE_AA,False)
            cv2.imwrite('image/'+buf.decode()+'.jpg',frame)
            cap.release()
            # plt.imshow(frame)  
            frame = cv2.imread('image/'+buf.decode()+'.jpg')
            if not frame is None:
                connection.send(b"HTTP/1.1 200 OK\r\n\r\nok")
                connection.close()
            else:
                connection.send(b"HTTP/1.1 202 OK\r\n\r\nerrer")
                connection.close()                
        else :
            cap.release()
            connection.send(b"HTTP/1.1 202 OK\r\n\r\nerrer")
            connection.close()            
        
    except Exception as e :
        connection.send(b"HTTP/1.1 202 OK\r\n\r\ntime out")
        connection.close()
    

    

while True:
    connection,address = server.accept()
    thread = threading.Thread(target=Server, args=(connection,address))
    thread.start()
connection.close()





